#include "executelogdlg.h"
#include "timedtaskmanager.h"
#include "router/systemMonitor/timedTask/edittaskdlg.h"
#include "router/systemMonitor/timedTask/jobdetaildlg.h"

#include <QMouseEvent>

TimedTaskManager::TimedTaskManager(Ui::Index *ui,QObject *parent)
    : QObject{parent}
{
    this->ui = ui;
    //图标
    QPixmap pix(":/image/res/search.jpg");
    pix.scaled(25,25);
    ui->btn_task_hideSearch->setIcon(pix);
    ui->btn_task_search->setIcon(pix);
    QPixmap freshPix(":/image/res/refresh.jpg");
    ui->btn_task_reset->setIcon(freshPix.scaled(25,25));
    ui->btn_task_refresh->setIcon(freshPix.scaled(25,25));
    ui->tableWidget_task->setEditTriggers(QAbstractItemView::NoEditTriggers);
    ui->tableWidget_task->setSelectionBehavior(QAbstractItemView::SelectRows);

    init();

    //隐藏搜索
    connect(ui->btn_task_hideSearch,&QPushButton::clicked,this,[=](){
        ui->widget_88->setHidden(!ui->widget_88->isHidden());
    });
    //    //下一页
    connect(ui->btn_task_next,&QPushButton::clicked,this,[=](){
        ui->btn_task_next->setEnabled(0);
        currentPage ++;
        getList();
        initTable();
        initPageInfo();
    });
    //上一页
    connect(ui->btn_task_pervious,&QPushButton::clicked,this,[=](){
        ui->btn_task_pervious->setEnabled(0);
        currentPage --;
        getList();
        initTable();
        initPageInfo();
    });
    //跳转页
    connect(ui->lineEdit_task_gotoPage,&QLineEdit::returnPressed,this,[=](){
        int page = ui->lineEdit_task_gotoPage->text().toInt();
        ui->lineEdit_task_gotoPage->clear();
        if(page < 1 || page > totalPage){
            ui->lineEdit_task_gotoPage->setStyleSheet("border:1px solid red;");
            return;
        }
        ui->lineEdit_task_gotoPage->setStyleSheet("");
        currentPage = page;
        getList();
        initTable();
        initPageInfo();
    });
    //    每页大小
    connect(ui->comboBox_task_pageItem,SIGNAL(currentIndexChanged(int)),this,SLOT(pageSizeChanged(int)));
    //    重置
    connect(ui->btn_task_reset,&QPushButton::clicked,this,[=](){
        ui->btn_task_reset->setEnabled(0);
        init();
        ui->btn_task_reset->setEnabled(1);
    });
    //搜索
    connect(ui->btn_task_search,&QPushButton::clicked,this,[=](){
        getList();
        initTable();
        initPageInfo();
    });
    //刷新
    connect(ui->btn_task_refresh,&QPushButton::clicked,this,[=](){
        getList();
        initTable();
        initPageInfo();
    });
    connect(ui->btn_task_add,&QPushButton::clicked,this,[=](){
        EditTaskDlg *e = new EditTaskDlg(0,sys_job_group);
        e->setAttribute(Qt::WA_DeleteOnClose);
        connect(e,&EditTaskDlg::success,this,[=](){
            getList();
            initTable();
            initPageInfo();
        });
        e->exec();
    });
    //修改
    connect(ui->btn_task_update,&QPushButton::clicked,this,[=](){
        int index = ui->tableWidget_task->currentRow();
        if(index < 0) return;
        QString id = ui->tableWidget_task->item(index,0)->text();
        EditTaskDlg *e = new EditTaskDlg(id.toLongLong(),sys_job_group);
        e->setAttribute(Qt::WA_DeleteOnClose);
        connect(e,&EditTaskDlg::success,this,[=](){
            getList();
            initTable();
            initPageInfo();
        });
        e->exec();
    });
    //批量删除
    connect(ui->btn_task_del,SIGNAL(clicked()),this,SLOT(deleteByIds()));
    //导出
    connect(ui->btn_task_export,&QPushButton::clicked,this,[=](){
        utils.exportExcel(ui->tableWidget_task,"定时任务表格");
    });
    connect(ui->btn_task_log,&QPushButton::clicked,this,[=](){
        ExecuteLogDlg *e = new ExecuteLogDlg(sys_job_group);
        e->setAttribute(Qt::WA_DeleteOnClose);
        e->exec();
    });
}

bool TimedTaskManager::eventFilter(QObject *obj, QEvent *event)
{
    if (event->type() == QEvent::MouseButtonPress){
        QMouseEvent *mouseEvent = static_cast<QMouseEvent*>(event);
        if(mouseEvent->button() == Qt::LeftButton){
            return true;
        }else{
            return false;
        }
    }else if(event->type() == QEvent::Enter){
        return true;
    }else if(event->type() == QEvent::Leave){
        if(obj == moreDlg){
            moreDlg->close();
        }
        return true;
    }else if(event->type() == QEvent::ActivationChange){
        if(QApplication::activeWindow() != moreDlg){
            moreDlg->close();
        }
        return true;
    }else{
        return QObject::eventFilter(obj, event);
    }
}

void TimedTaskManager::pageSizeChanged(int index)
{
    switch (index) {
    case 0:
        pageSize = 5;
        break;
    case 1:
        pageSize = 10;
        break;
    case 2:
        pageSize = 20;
        break;
    case 3:
        pageSize = 50;
        break;
    case 4:
        pageSize = 100;
        break;
    default:
        break;
    }
    currentPage = 1;
    getList();
    initTable();
    initPageInfo();
}

void TimedTaskManager::deleteByIds()
{
    QList<QTableWidgetItem*> items = ui->tableWidget_task->selectedItems();
    if(items.size() == 0) return;
    int rowCount = items.size() / 5;    //选中的行数
    QString ids;
    for(int i = 0;i< rowCount;i++){
        int index = ui->tableWidget_task->row(items.at(i * 5));
        if(i != rowCount - 1){
            ids += ui->tableWidget_task->item(index,0)->text() + ",";
        }else{
            ids += ui->tableWidget_task->item(index,0)->text();
        }
    }
    int flag = QMessageBox::question(0,"提示","确定删除所选项吗?",QMessageBox::Yes|QMessageBox::No);
    if(flag == QMessageBox::No) return;
    QByteArray *bytes = api.deleteItems(ids);
    QJsonObject obj = QJsonDocument::fromJson(*bytes).object();
    if(200 == obj.value("code").toInt()){
        QMessageBox::warning(0,"提示",obj.value("msg").toString());
        getList();
        initTable();
        initPageInfo();
    }
}

void TimedTaskManager::init()
{
    getDictList();
    initSearchArea();
    getList();
    initTable();
    initPageInfo();
}

void TimedTaskManager::getDictList()
{
    sys_job_group.clear();
    QByteArray *data = utils.getDictType("sys_job_group");
    QJsonObject obj = QJsonDocument::fromJson(*data).object();
    QJsonArray arr = obj.value("data").toArray();
    for(int i = 0;i< arr.size();i++){
        sys_job_group.append(DictData::toDictData(arr.at(i).toObject()));
    }
    sys_job_status.clear();
    data = utils.getDictType("sys_job_status");
    obj = QJsonDocument::fromJson(*data).object();
    arr = obj.value("data").toArray();
    for(int i = 0;i< arr.size();i++){
        sys_job_status.append(DictData::toDictData(arr.at(i).toObject()));
    }
}

void TimedTaskManager::initSearchArea()
{
    ui->lineEdit_task_taskName->clear();
    ui->comboBox_task_taskGroup->clear();
    ui->comboBox_task_status->clear();
    ui->comboBox_task_status->addItem("");
    for(int i = 0;i< sys_job_status.size();i++){
        ui->comboBox_task_status->addItem(sys_job_status.at(i).dictLabel,sys_job_status.at(i).dictValue);
    }
    ui->comboBox_task_taskGroup->addItem("");
    for(int i = 0;i< sys_job_group.size();i++){
        ui->comboBox_task_taskGroup->addItem(sys_job_group.at(i).dictLabel,sys_job_group.at(i).dictValue);
    }
}

void TimedTaskManager::getList()
{
    jobList.clear();
    QString taskName = ui->lineEdit_task_taskName->text();
    QString taskGroup = ui->comboBox_task_taskGroup->itemData(
                ui->comboBox_task_taskGroup->currentIndex()).value<QString>();
    QString status = ui->comboBox_task_status->itemData(
                ui->comboBox_task_status->currentIndex()).value<QString>();
    QByteArray *data = api.list(currentPage,pageSize,taskName,taskGroup,status);
    QJsonObject obj = QJsonDocument::fromJson(*data).object();
    QJsonArray arr = obj.value("rows").toArray();
    total = obj.value("total").toInt();
    for(int i = 0;i< arr.size();i++){
        jobList.append(Job::toJob(arr.at(i).toObject()));
    }
    if(total%pageSize == 0){
        totalPage = total / pageSize;
    }else{
        totalPage = total / pageSize + 1;
    }
    ui->label_task_count->setText("共"+QString::number(total)+"条");
}

void TimedTaskManager::initTable()
{
    ui->tableWidget_task->setSortingEnabled(0);
    ui->tableWidget_task->sortByColumn(-1, Qt::AscendingOrder);
    ui->tableWidget_task->clear();
    QStringList columnHeader;
    columnHeader << "任务编号" << "任务名称" << "任务组名" << "调用目标字符串" << "状态cron表达式" << "状态" << "操作";
    ui->tableWidget_task->setColumnCount(columnHeader.size());
    ui->tableWidget_task->setHorizontalHeaderLabels(columnHeader);
    ui->tableWidget_task->setRowCount(jobList.size());
    ui->tableWidget_task->setColumnWidth(0,70);
    ui->tableWidget_task->setColumnWidth(1,210);
    ui->tableWidget_task->setColumnWidth(3,250);
    ui->tableWidget_task->setColumnWidth(4,120);
    ui->tableWidget_task->setColumnWidth(5,70);
    ui->tableWidget_task->setColumnWidth(6,240);
    ui->tableWidget_task->setRowHeight(0,38);
    for(int i = 0;i< jobList.size();i++){
        QString id = QString::number(jobList.at(i).jobId);
        ui->tableWidget_task->setItem(i,0,new QTableWidgetItem(id));
        ui->tableWidget_task->setItem(i,1,new QTableWidgetItem(jobList.at(i).jobName));
        QString group;
        for (int i = 0; i < sys_job_group.size(); ++i) {
            if(sys_job_group.at(i).dictValue == jobList.at(i).jobGroup){
                group = sys_job_group.at(i).dictLabel;
            }
        }
        ui->tableWidget_task->setItem(i,2,new QTableWidgetItem(group));
        ui->tableWidget_task->setItem(i,3,new QTableWidgetItem(jobList.at(i).invokeTarget));
        ui->tableWidget_task->setItem(i,4,new QTableWidgetItem(jobList.at(i).cronExpression));
        QCheckBox *box = new QCheckBox();
        connect(box,&QCheckBox::clicked,this,[=](){
            QString tip = "确定要【%1】【%2】任务吗?";
            tip = QString(tip).arg(!box->isChecked() ? "停用" : "启用").arg(jobList.at(i).jobName);
            int flag = QMessageBox::question(0,"系统提示",tip,QMessageBox::Yes|QMessageBox::No);
            if(flag == QMessageBox::Yes){
                QByteArray *data = api.changeStatus(id,jobList.at(i).status == "0" ? "1" : "0");
                QJsonObject obj = QJsonDocument::fromJson(*data).object();
                if(obj.value("code") == 200){
                    QMessageBox::information(0,"提示",obj.value("msg").toString());
                }
            }else{
                box->setChecked(!box->isChecked());
            }
        });
        box->setCheckState(jobList.at(i).status == "0" ? Qt::Checked : Qt::Unchecked);
        QWidget *widget = new QWidget();
        QHBoxLayout *layout = new QHBoxLayout();
        layout->addWidget(box);
        layout->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
        widget->setLayout(layout);
        ui->tableWidget_task->setCellWidget(i,5,widget);

        QWidget *tmp_widget = new QWidget();
        QHBoxLayout *tmp_layout = new QHBoxLayout();
        QPushButton *btnUpdate = new QPushButton;
        QPushButton *btnDelete = new QPushButton;
        QPushButton *btnMore = new QPushButton;
        connect(btnDelete,&QPushButton::clicked,this,[=](){
            int flag  = QMessageBox::question(0,"提示","确定删除该项吗?",QMessageBox::Yes|QMessageBox::No);
            if(flag == QMessageBox::Yes){
                QByteArray *bytes = api.deleteItems(id);
                QJsonObject obj = QJsonDocument::fromJson(*bytes).object();
                if(200 == obj.value("code").toInt()){
                    QMessageBox::warning(0,"提示",obj.value("msg").toString());
                    getList();
                    initTable();
                    initPageInfo();
                }
            }
        });
        connect(btnUpdate,&QPushButton::clicked,this,[=](){;
            EditTaskDlg *e = new EditTaskDlg(id.toLongLong(),sys_job_group);
            e->setAttribute(Qt::WA_DeleteOnClose);
            connect(e,&EditTaskDlg::success,this,[=](){
                getList();
                initTable();
                initPageInfo();
            });
            e->exec();
        });
        connect(btnMore,&QPushButton::clicked,this,[=](){;
            moreDlg = new QDialog;
            moreDlg->installEventFilter(this);
            QVBoxLayout *l = new QVBoxLayout(moreDlg);
            moreDlg->setWindowFlag(Qt::FramelessWindowHint);
            QPushButton *invokeOnce = new QPushButton;
            QPushButton *jobDetail = new QPushButton;
            QPushButton *invokeLog = new QPushButton;
            invokeOnce->setText("执行一次");
            invokeOnce->setIcon(QIcon(":/svg/res/svg/execute.svg"));
            jobDetail->setText("任务详细");
            jobDetail->setIcon(QIcon(":/svg/res/svg/eye-open.svg"));
            invokeLog->setText("调度日志");
            invokeLog->setIcon(QIcon(":/svg/res/svg/swagger.svg"));
            l->addWidget(invokeOnce);
            l->addWidget(jobDetail);
            l->addWidget(invokeLog);
            moreDlg->move(btnMore->mapToGlobal(QPoint(0,0)).x(),
                          btnMore->mapToGlobal(QPoint(0,0)).y() + 25);
            moreDlg->show();
            connect(invokeOnce,&QPushButton::clicked,this,[=](){
                int flag  = QMessageBox::question(0,"提示","确认要立即执行一次" + jobList.at(i).jobName + "任务吗？",QMessageBox::Yes|QMessageBox::No);
                if(flag == QMessageBox::Yes){
                    QByteArray *data = api.run(id,jobList.at(i).jobGroup);
                    QJsonObject obj = QJsonDocument::fromJson(*data).object();
                    if(obj.value("code").toInt() == 200){
                        QMessageBox::warning(0,"提示",obj.value("msg").toString());
                    }
                }
            });
            connect(jobDetail,&QPushButton::clicked,this,[=](){
                moreDlg->close();
                JobDetailDlg *a = new JobDetailDlg(id,sys_job_group);
                a->setAttribute(Qt::WA_DeleteOnClose);
                a->exec();
            });
            connect(invokeLog,&QPushButton::clicked,this,[=](){
                ExecuteLogDlg *e = new ExecuteLogDlg(sys_job_group,id);
                e->setAttribute(Qt::WA_DeleteOnClose);
                e->exec();
            });
        });
        btnDelete->setText("🗑删除");
        btnDelete->setStyleSheet("QPushButton {padding: 5px 10px;border-style: none;border-radius: 10px;background-color: rgb(232, 244, 255);color: black;}QPushButton:hover {background-color: rgb(24, 144, 255);}QPushButton:pressed {background-color: rgb(24, 144, 200);}");
        btnUpdate->setText("🖍修改");
        btnUpdate->setStyleSheet("QPushButton {padding: 5px 10px;border-style: none;border-radius: 10px;background-color: rgb(231, 250, 240);color: black;}QPushButton:hover {background-color: rgb(19, 206, 102);}QPushButton:pressed {background-color: rgb(19, 150, 102);}");
        btnMore->setText("》更多");
        btnMore->setStyleSheet("QPushButton {padding: 5px 10px;border-style: none;border-radius: 10px;background-color: rgb(255, 237, 237);color: black;}QPushButton:hover {background-color: rgb(255, 73, 73);}QPushButton:pressed {background-color: rgb(200, 73, 73);}");
        tmp_layout->addWidget(btnUpdate);
        tmp_layout->addWidget(btnDelete);
        tmp_layout->addWidget(btnMore);
        tmp_widget->setLayout(tmp_layout);
        tmp_layout->setContentsMargins(0,0,0,0);
        ui->tableWidget_task->setCellWidget(i,6,tmp_widget);
    }
    // 设置单元格内容居中对齐
    for (int row = 0; row < ui->tableWidget_task->rowCount(); ++row) {
        for (int column = 0; column < ui->tableWidget_task->columnCount(); ++column) {
            QTableWidgetItem* item = ui->tableWidget_task->item(row, column);
            if (item) {
                item->setTextAlignment(Qt::AlignCenter);
            }
        }
    }
    ui->tableWidget_task->setSortingEnabled(1);
}

void TimedTaskManager::initPageInfo()
{
    if(currentPage == 1){
        ui->btn_task_pervious->setEnabled(0);
    }else{
        ui->btn_task_pervious->setEnabled(1);
    }
    ui->label_task_currentPage->setText(QString::number(currentPage));
    if(currentPage == totalPage){
        ui->btn_task_next->setEnabled(0);
    }else{
        ui->btn_task_next->setEnabled(1);
    }
}
